package cn.edu.niit.studyspace.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import cn.edu.niit.studyspace.R;
import cn.edu.niit.studyspace.fragment.CalculatingFragment;
import cn.edu.niit.studyspace.fragment.SchoolTimetableFragment;

public class ToolBoxActivity extends AppCompatActivity {
    private Fragment currentFragment = null;//初始Fragment
    private Fragment calculatorFragment = null;
    private Fragment schoolTimetable = null;
    private Button btnSchoolTable;
    private Button btnCurrent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tool_box);
        initView();
        initListeners();
        switchFragment(calculatorFragment).commit();
    }

    private void initListeners() {
        btnCurrent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchFragment(calculatorFragment).commit();

            }
        });

        btnSchoolTable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchFragment(schoolTimetable).commit();
            }
        });
    }

    private void initView() {
        currentFragment = new CalculatingFragment();
        calculatorFragment = new CalculatingFragment();
        schoolTimetable = new SchoolTimetableFragment();
        btnSchoolTable = findViewById(R.id.btn_school_timetable);
        btnCurrent = findViewById(R.id.btn_calculator);
    }


    private FragmentTransaction switchFragment(Fragment targerFragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!targerFragment.isAdded()) {
            //未加载过
            transaction.hide(currentFragment);//隐藏默认Fragment
            transaction.add(R.id.content_view, targerFragment, targerFragment.getClass().getName());//添加
        } else {
            //加载过
            transaction.hide(currentFragment);//隐藏默认
            transaction.show(targerFragment);//加载现在
        }
        currentFragment = targerFragment;
        return transaction;
    }

    public void onClick(View view) {
        ((CalculatingFragment) getSupportFragmentManager().findFragmentByTag(CalculatingFragment.class.getName())).onClick(view);
    }


}
